package com.xc.hotelmgr.order.modules.ctrip.service;

import com.alibaba.fastjson.JSONObject;
import com.xc.hotelmgr.order.common.utils.Constant;
import com.xc.hotelmgr.order.common.utils.GeneValidateVQResponse;
import com.xc.hotelmgr.order.common.utils.XmlUtils;
import com.xc.hotelmgr.order.modules.ali.to.validaterq.request.ValidateRQ;
import com.xc.hotelmgr.order.modules.ali.to.validaterq.response.ValidateRQResult;
import com.xc.hotelmgr.order.modules.ctrip.to.saveorder.request.GuestCount;
import com.xc.hotelmgr.order.modules.ctrip.to.saveorder.request.GuestCounts;
import com.xc.hotelmgr.order.modules.ctrip.sdk.CtripInterface;
import com.xc.hotelmgr.order.modules.ctrip.sdk.CtripClient;
import com.xc.hotelmgr.order.modules.ctrip.sdk.CtripDtInfo;
import com.xc.hotelmgr.order.modules.ctrip.to.validate.request.*;
import com.xc.hotelmgr.order.modules.order.entity.DtOrderChannelsEntity;
import com.xc.hotelmgr.order.modules.order.service.DtOrderChannelsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;
@Slf4j
@Service("ctripValidateService")
public class CtripValidateService {
    @Autowired
    private DtOrderChannelsService dtOrderChannelsService;

    /**
     * 检查房型是否可预订（419f7a688e3c45f481d295708b870323）
     * @param validateRQ
     * @return
     */
    public String validateRQ(ValidateRQ validateRQ) throws InterruptedException {
        CtripCheck ctripCheck = new CtripCheck();
        ctripCheck.setVersion(1);
        ctripCheck.setTransactionIdentifier(UUID.randomUUID().toString().replaceAll("-", ""));
        HotelRef hotelRef = new HotelRef();
        hotelRef.setHotelCode(validateRQ.getHotelId().substring(2));
        StayDateRange stayDateRange = new StayDateRange();
        stayDateRange.setStart(validateRQ.getCheckIn());
        stayDateRange.setEnd(validateRQ.getCheckOut());
        RatePlanCandidate ratePlanCandidate = new RatePlanCandidate();
//        ratePlanCandidate.setRoomID(validateRQ.getRoomTypeId().substring(2));
        ratePlanCandidate.setRoomID(validateRQ.getRatePlanCode().substring(2));
//        ratePlanCandidate.setRatePlanID(validateRQ.getRatePlanCode().substring(2));
        ratePlanCandidate.setRatePlanCategory("501");
        ratePlanCandidate.setPrepaidIndicator(true);
        RatePlanCandidates ratePlanCandidates = new RatePlanCandidates();
        ratePlanCandidates.setRatePlanCandidate(ratePlanCandidate);
        GuestCount guestCount = new GuestCount();
        guestCount.setCount(Integer.valueOf(validateRQ.getCustomerNumber()));
        GuestCounts guestCounts = new GuestCounts();
        guestCounts.setGuestCount(guestCount);
        RoomStayCandidate roomStayCandidate = new RoomStayCandidate();
        roomStayCandidate.setGuestCounts(guestCounts);
        roomStayCandidate.setQuantity(Integer.valueOf(validateRQ.getRoomNum()));
        RoomStayCandidates roomStayCandidates = new RoomStayCandidates();
        roomStayCandidates.setRoomStayCandidate(roomStayCandidate);
        TPA_Extensions tpa_extensions = new TPA_Extensions();
        //最晚到店时间（无）
        tpa_extensions.setLateArrivalTime(validateRQ.getCheckIn());
        Criterion criterion = new Criterion();
        criterion.setHotelRef(hotelRef);
        criterion.setStayDateRange(stayDateRange);
        criterion.setRatePlanCandidates(ratePlanCandidates);
        criterion.setRoomStayCandidates(roomStayCandidates);
        criterion.setTPA_Extensions(tpa_extensions);
        HotelSearchCriteria hotelSearchCriteria = new HotelSearchCriteria();
        hotelSearchCriteria.setCriterion(criterion);
        AvailRequestSegment availRequestSegment = new AvailRequestSegment();
        availRequestSegment.setHotelSearchCriteria(hotelSearchCriteria);
        AvailRequestSegments availRequestSegments = new AvailRequestSegments();
        availRequestSegments.setAvailRequestSegment(availRequestSegment);
        ctripCheck.setAvailRequestSegments(availRequestSegments);
        ctripCheck.setTimeStamp(new Date().toString());
        CtripDtInfo ctripDtInfo = new CtripDtInfo();
        ctripDtInfo.setJsonData(JSONObject.toJSONString(ctripCheck));
        String userName = validateRQ.getAuthenticationToken().getUsername();
        DtOrderChannelsEntity dtOrderChannelsEntity = dtOrderChannelsService.sqlSelectKey(Constant.Channel.Ctrip.getValue(), userName);
        //构造返回
        ValidateRQResult validateRQResponse = null;
        if (dtOrderChannelsEntity == null) {
            log.error("携程：请配置飞猪接口用户名为{}的店铺对应的携程渠道账号",userName);
            validateRQResponse = GeneValidateVQResponse.gene(false, validateRQ.getDailyInfos(), "1");
            return XmlUtils.toXML(validateRQResponse);
        }
        ctripDtInfo.setAID(Integer.valueOf(dtOrderChannelsEntity.getAccessKey()));
        ctripDtInfo.setSID(dtOrderChannelsEntity.getSid());
        ctripDtInfo.setKey(dtOrderChannelsEntity.getSecretKey());
        ctripDtInfo.setAccess_Token(dtOrderChannelsEntity.getAccessToken());
        ctripDtInfo.setUniqueID(dtOrderChannelsEntity.getUniqueId());
        ctripDtInfo.setRefresh_Token(dtOrderChannelsEntity.getRefreshToken());
        ctripDtInfo.setICODE(CtripInterface.ValidateRQ.getValue());
        log.info("携程：下单前校验,酒店ID：{},房型ID：{},RP:{},请求报文:{}",validateRQ.getHotelId(),validateRQ.getRoomTypeId(),validateRQ.getRatePlanCode(),ctripDtInfo.getJsonData());
        try {
            String valiResult = CtripClient.excuteReq(ctripDtInfo);
            //如果session失效，休眠2秒钟
            if (valiResult.contains("INVALID_TOKEN")) {
                // 睡眠2秒后在执行
                Thread.sleep(2000);
                return validateRQ(validateRQ);
            } else {
                validateRQResponse = GeneValidateVQResponse.gene(true, validateRQ.getDailyInfos(), "1");
                log.info("携程下单前校验,酒店ID：{},房型ID：{},RP:{},返回信息:{}",validateRQ.getHotelId(),validateRQ.getRoomTypeId(),validateRQ.getRatePlanCode(),validateRQResponse);
            }
        } catch (Exception ex) {
            validateRQResponse = GeneValidateVQResponse.gene(false, validateRQ.getDailyInfos(), "1");
            log.error("携程下单前校验异常,酒店ID：{},房型ID：{},RP:{},异常信息：{}",validateRQ.getHotelId(),validateRQ.getRoomTypeId(),validateRQ.getRatePlanCode(), ex.toString());
        }
        return XmlUtils.toXML(validateRQResponse);
    }

}
